import ReactDOM from 'react-dom'
export default function move (obj) {
  let bln = true
  var btn = ReactDOM.findDOMNode(obj)
  // let appVersion = window.navigator.appVersion
  // if (appVersion.toLowerCase().includes('window')) {
  // } else {
  // }

  // PC模式
  btn.addEventListener('mousedown', mousedown)
  // 手机模式
  btn.addEventListener('touchstart', touchstart)
  // PC模式
  function mousedown (e) { //鼠标按下事件
    e = e || document.event //事件对象
    var gapX = e.clientX - offset(this).left
    var gapY = e.clientY - offset(this).top
    var maxX = document.documentElement.clientWidth - this.offsetWidth
    var maxY = document.documentElement.clientHeight - this.offsetHeight

    document.addEventListener('mousemove', mousemove)
    function mousemove (e) { //鼠标移动事件
      bln = false
      e = e || document.event
      var x = e.clientX - gapX
      var y = e.clientY - gapY
      // 边界判断
      if (x < 0) {
        x = 0
      }
      if (x > maxX) {
        x = maxX
      }
      if (y < 0) {
        y = 0
      }
      if (y > maxY) {
        y = maxY
      }
      //赋值给left和top
      btn.style.top = y + 15 + 'px'
      btn.style.left = x + 'px'
    }
    document.addEventListener('mouseup', mouseup)
    function mouseup () { //鼠标抬起事件
      //清除移动和抬起事件
      this.removeEventListener('mousemove', mousemove)
      this.removeEventListener('mouseup', mouseup)
      obj.props.onClick(false, bln)
      bln = true
    }
  }

  // 手机模式
  function touchstart (e) {
    e = e || document.event //事件对象
    const touch = e.changedTouches.item(0)
    const gapX = touch.clientX - offset(this).left
    const gapY = touch.clientY - offset(this).top
    const maxX = document.documentElement.clientWidth - this.offsetWidth
    const maxY = document.documentElement.clientHeight - this.offsetHeight
    document.ontouchmove = function (e) { //鼠标移动事件
      e = e || document.event
      const touch = e.changedTouches.item(0)
      var x_now = touch.clientX - gapX
      var y_now = touch.clientY - gapY + 15
      // 边界判断
      if (x_now < 0) {
        x_now = 0
      }
      if (x_now > maxX) {
        x_now = maxX
      }
      if (y_now < 0) {
        y_now = 0
      }
      if (y_now > maxY) {
        y_now = maxY
      }
      //赋值给left和top
      btn.style.top = y_now + 'px'
      btn.style.left = x_now + 'px'
    }
    document.ontouchend = function () { //鼠标抬起事件
      document.ontouchmove = null
      document.ontouchend = null
    }
  }
  // 封装获取元素到body的距离
  function offset (dom) {
    var l = 0
    var t = 0
    l -= dom.clientLeft
    t -= dom.clientTop
    while (dom) {
      l = l + dom.offsetLeft + dom.clientLeft
      t = t + dom.offsetTop + dom.clientTop
      dom = dom.offsetParent
    }
    return {
      left: l,
      top: t
    }
  }
}
